package com.cys.markdown.doc.admin.common.handler;

import com.cys.common.data.RespCodeEnum;
import com.cys.common.pojo.RespEntity;
import com.cys.common.util.base.IpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理类
 * Created by caiyushen on 2018/9/7.
 */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class);


    /**
     * 【shiro-权限校验】异常捕获
     *
     * @ExceptionHandler来增强所有的@requestMapping方法。
     * @ExceptionHandler(Exception.class) 用来捕获@requestMapping的方法中所有抛出的exception。
     */
    @ExceptionHandler(org.apache.shiro.authz.UnauthorizedException.class)
    @ResponseBody
    public RespEntity permissionExceptionHandler(HttpServletRequest request, org.apache.shiro.authz.UnauthorizedException e) {
        logger.info("method[permissionExceptionHandler] requestUrl:" + request.getRequestURL());
        logger.warn("method[permissionExceptionHandler] ip:" + new IpUtil().getRemoteHost(request));
        logger.warn(e.getMessage(), e);
        return new RespEntity(RespCodeEnum.unauthorized);
    }

    /**
     * 声明要捕获404异常
     *
     * @ExceptionHandler来增强所有的@requestMapping方法。
     * @ExceptionHandler(Exception.class) 用来捕获@requestMapping的方法中所有抛出的exception。
     */
    @ExceptionHandler(org.springframework.web.servlet.NoHandlerFoundException.class)
    @ResponseBody
    public RespEntity noHandlerFoundExceptionHandler(HttpServletRequest request, Exception e) {
        logger.info("method[noHandlerFoundExceptionHandler] requestUrl:" + request.getRequestURL());
        logger.warn("method[noHandlerFoundExceptionHandler] ip:" + new IpUtil().getRemoteHost(request));
        logger.warn(e.getMessage(), e);
        return new RespEntity(RespCodeEnum.null_request);
    }

    /**
     * 【全局】声明要捕获的异常
     *
     * @ExceptionHandler来增强所有的@requestMapping方法。
     * @ExceptionHandler(Exception.class) 用来捕获@requestMapping的方法中所有抛出的exception。
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RespEntity defaultExceptionHandler(HttpServletRequest request, Exception e) {
        logger.info("method[defaultExceptionHandler] requestUrl:" + request.getRequestURL());
        logger.warn("method[defaultExceptionHandler] ip:" + new IpUtil().getRemoteHost(request));
        logger.warn(e.getMessage(), e);
        return new RespEntity(RespCodeEnum.error);
    }


}




